from goods.models import GoodsChannel


def get_categories():
    """返回商品分类数据"""
    # 定义一个空字典
    categories = {}
    # 获取到当前数据库的数据，并且按照顺序排列
    goods_channels_qs = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历当前的查询集，拼接数据
    for goods_channel in goods_channels_qs:
         group_id = goods_channel.group_id

         # 判断当前的组别是不是有
         if group_id not in categories:
             # 如果当前组号在字典的key中不存时,再去添加数据初始格式
             categories[group_id] = {'channels': [],'sub_cats':[]}

         # 获取一组数据对象
         cat1 = goods_channel.category
         cat1.url = goods_channel.url
         categories[group_id]['channels'].append(cat1)


         # 获取对象2，同时将对象3作为对象2的属性加入
         cat2_qs = cat1.subs.all()
         for cat2 in cat2_qs:
             cat3_qs = cat2.subs.all()
             cat2.sub_cats = cat3_qs
             categories[group_id]['sub_cats'].append(cat2)
    return categories


def get_breadcrumb(category):
    """获取面包屑导航方法"""
    # 获取数据库中该id的三级目录,请注意传进来的 category是对象；
    # 获取1获取其1级的对象；
    cat1 = category.parent.parent
    # 给1级对象中新增url;
    cat1.url = cat1.goodschannel_set.all()
    # 拼接成字典格式，并返回;
    breadcrumb = {
        'cat1': cat1,
        'cat2': category.parent,
        'cat3': category,
    }
    return breadcrumb



